package com.kevin.j2eeToolBox.lock;

public class SynchronizedTest1 {

	/**
	 * @param args
	 */
	public static void main(String[] args) {

		Example example = new Example();
		Thread1 thread1 = new Thread1(example);
		Thread2 thread2 = new Thread2(example);

		thread1.start();
		thread2.start();
	}
}

class Example {

	public synchronized void execute1() {

		for (int i = 0; i < 20; i++) {
			try {
				Thread.sleep((long) (Math.random() * 1000));
			} catch (InterruptedException e) {
				e.printStackTrace();
			}

			System.out.println("hello: " + i);
		}
	}

	public synchronized void execute2() {

		for (int i = 0; i < 20; i++) {
			try {
				Thread.sleep((long) (Math.random() * 1000));
			} catch (InterruptedException e) {
				e.printStackTrace();
			}

			System.out.println("world: " + i);
		}
	}
}

class Thread1 extends Thread {

	private Example example;

	public Thread1(Example example) {

		this.example = example;
	}

	@Override
	public void run() {
		this.example.execute1();
	}
}

class Thread2 extends Thread {

	private Example example;

	public Thread2(Example example) {

		this.example = example;
	}

	@Override
	public void run() {
		this.example.execute2();
	}
}
